﻿using Qy.Core;
using SqlSugar;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Qy.Scenario;

[AppService]
public class DictCatService : QyRepository<DictCat>
{
    public DictCatService(ApplicationContext applicationContext) : base(applicationContext)
    {
    }

    public async Task<PagedInfo<DictCat>> GetPageListAsync(QueryDictCat parm)
    {
        return await Queryable()
                .WhereIF(!string.IsNullOrEmpty(parm.CatName), (data) => data.CatName.Contains(parm.CatName))
                .OrderBy((data) => data.Id, OrderByType.Desc)
                .ToPageAsync(parm);
    }


    /// <summary>
    /// 判断是否存在
    /// </summary>
    /// <returns></returns>
    public async Task<bool> GetByCodeAsync(string code)
    {
        return await Queryable().AnyAsync(data=>data.CatCode == code);
    }

    public async Task<int> UpdateDelCache(DictCat editDictCat)
    {
        DictCat dictCat = await GetIdAsync(editDictCat.Id);
        if (dictCat == null) return 0;
        if (dictCat.CatCode != editDictCat.CatCode && await GetByCodeAsync(editDictCat.CatCode) == false)
            return -2;//判断代码是否重复
        dictCat.Type = editDictCat.Type;
        dictCat.CatCode = editDictCat.CatCode;
        dictCat.CatName = editDictCat.CatName;
        dictCat.Remark = editDictCat.Remark;
        dictCat.Status = editDictCat.Status;
        return await UpdateAndDelCacheAsync(dictCat);
    }


    public async Task<bool> DeleteDelCache(int id)
    {
        bool find = await Context.Queryable<DictData>().AnyAsync(data => data.Cid == id); 
        if (find) 
            return false;
        return await DeleteAndDelCacheAsync(id) > 0;
    }

    public async Task<IEnumerable<DictCat>> GetListAsync(QueryDictCat query = null)
    {
        IEnumerable<DictCat> dictCats = await GetAllListAsync("Id desc");
        if (query == null)
            return dictCats;
        return dictCats.Take(query.PageSize);
    }
}
